﻿using KingsSharp.Common.Extensions;
using KingsSharp.Common.Infrastructure;
using CRM.Admin.Contracts.Model.Sys;
using System.Collections.Generic;
using System.Linq;

namespace CRM.Admin
{
    /// <summary>
    /// 菜单集合单例
    /// 程序首次运行即缓存进单例
    /// </summary>
    public class MenuItem : Singleton<MenuItem>
    {
        private List<MenuCatalog> Catalogs = new List<MenuCatalog>();

        private List<MenuNode> MenuNodes = new List<MenuNode>();

        private MenuItem()
        {

        }
        public ICollection<MenuCatalog> CatalogItems
        {
            get { return Catalogs; }
        }
        public ICollection<MenuNode> MenuNodeItems
        {
            get { return MenuNodes; }
        }
        /// <summary>
        /// 获取菜单
        /// </summary>
        /// <param name="corpnumber"></param>
        /// <returns></returns>
        public ICollection<MenuCatalog> GetCatalogTree()
        {
            var rootCatalogs = Catalogs.Where(a => a.ParentMenuCatalog == null).ToList();


            ICollection<MenuCatalog> menuTree = Catalogs.RenderTree<MenuCatalog, MenuCatalog>(rootCatalogs,
                (catalog, level) =>
                {
                    List<MenuNode> nodes = new List<MenuNode>();
                    MenuNodeItems.Where(a => a.CatalogId == catalog.Id).ToList()
                        .ForEach(a => { nodes.Add(a); });
                    return new MenuCatalog() { Id = catalog.Id, Name = catalog.Name, IconText = catalog.IconText, IconColor = catalog.IconColor, Type = catalog.Type, Menus = nodes, CataLogs = new List<MenuCatalog>() };
                }, (catalog, sources) =>
                {
                    return sources.Where(a => a.ParentMenuCatalog != null && a.ParentMenuCatalog.Id == catalog.Id).ToList();
                }, (parentNode, newNode) =>
                {
                    if (parentNode.CataLogs == null)
                    {
                        parentNode.CataLogs = new List<MenuCatalog>();
                    }
                    parentNode.CataLogs.Add(newNode);
                });
            return menuTree;
        }
    }
}